import { Button } from "@/components/ui/btn/button1";
import { Input } from "@/components/ui/input/input1";
import { LabelInput } from "@/components/ui/input/label_input";
import { useEffect, useState } from "react";
import {
  GenerateOption,
  GenerateSelector,
} from "./components/generate_selector";
import { selectedOptions } from "@/api/view/pages/generate_api";
import { toast } from "sonner";
import { GenerateDown } from "./components/generate_down";

export default function Generate({ selectedType, setIndexUiError }: NavIndex) {
  const [prompt, setPrompt] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [selectedDirection, setSelectedDirection] = useState("");
  const [articleCount, setArticleCount] = useState("1");
  const [options, setOptions] = useState<GenerateOption[]>([]);
  const [isLoadingOptions, setIsLoadingOptions] = useState(false);
  const [optionsError, setOptionsError] = useState<string>("");

  const [templateBatch, setTemplateBatch] = useState(() => {
    return localStorage.getItem("generateTemplateBatch") || "";
  });
  const [buildBatch, setBuildBatch] = useState(() => {
    return localStorage.getItem("generateBuildBatch") || "";
  });
  const [hasLocalError, setHasLocalError] = useState({
    prompt: false,
    articleCount: false,
    templateBatch: false,
    buildBatch: false,
    selectedModel: false,
  });

  const setSelectedModelError = (errorFlag: boolean) => {
    setHasLocalError((prev) => ({ ...prev, selectedModel: errorFlag }));
  };
  // ui值改变时，保存到localStorage
  useEffect(() => {
    localStorage.setItem("generateTemplateBatch", templateBatch);
    localStorage.setItem("generateBuildBatch", buildBatch);
  }, [templateBatch, buildBatch]);

  const virFetchOptions = async () => {
    setIsLoadingOptions(true);
    setOptionsError("");
    try {
      // sleep
      await new Promise((resolve) => setTimeout(resolve, 2000));
      if (templateBatch === "" || buildBatch === "") {
        throw new Error("请填写所有必填项");
      }
      setOptions(selectedOptions);
    } catch (error) {
      console.log(error);
      setOptionsError("获取选项失败");
    } finally {
      setIsLoadingOptions(false);
    }
  };

  const virHandleGenerate = async () => {
    // 重置错误状态
    setIndexUiError(false);

    setHasLocalError({
      prompt: false,
      articleCount: false,
      templateBatch: false,
      buildBatch: false,
      selectedModel: false,
    });
    // 验证所有必填字段
    const errorsIndex = !selectedType;
    const errorsLocal = {
      prompt: !prompt,
      articleCount: !articleCount,
      templateBatch: !templateBatch,
      buildBatch: !buildBatch,
      selectedModel: !selectedDirection,
    };
    setIndexUiError(errorsIndex);
    setHasLocalError(errorsLocal);
    if (errorsIndex || Object.values(errorsLocal).some((v) => v)) {
      toast.error("请填写所有必填项", { position: "top-center" });
      return;
    }

    setIsLoading(true);
    try {
      // sleep
      await new Promise((resolve) => setTimeout(resolve, 2000));
      // 模拟请求
      toast.success("模拟了生成！", { position: "top-center" });
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex h-full min-h-0 flex-col">
      <div className="my-auto flex flex-row justify-center space-x-4">
        <div className="flex flex-row space-x-4 pb-6">
          <LabelInput
            className="w-48"
            label="模板批次"
            value={templateBatch}
            onChange={(e) => {
              setTemplateBatch(e.target.value);
            }}
            errorFlag={hasLocalError.templateBatch}
            placeholder="请输入目标模板的批次"
          ></LabelInput>
          <LabelInput
            className="w-48"
            label="生成批次"
            value={buildBatch}
            onChange={(e) => {
              setBuildBatch(e.target.value);
            }}
            errorFlag={hasLocalError.buildBatch}
            placeholder="请输入生成的批次"
          ></LabelInput>
        </div>
        <div className="my-auto mb-6 flex space-x-4">
          <GenerateSelector
            value={selectedDirection}
            onValueChange={setSelectedDirection}
            options={options}
            placeholder="选择一个模版"
            errorFlag={hasLocalError.selectedModel}
            className="w-36"
            onOpenChange={() => {
              virFetchOptions();
            }}
            setErrorFlag={setSelectedModelError}
            isLoading={isLoadingOptions}
            errorMessage={optionsError}
          />
          <Input
            placeholder="内容生产提示词"
            className={`w-96 bg-background`}
            value={prompt}
            onChange={(e) => {
              setPrompt(e.target.value);
            }}
            errorFlag={hasLocalError.prompt}
          />
          <div className="flex items-center space-x-2">
            <Input
              type="number"
              min="1"
              max="5" // 添加 max 属性
              value={articleCount}
              onChange={(e) => {
                let value = e.target.value.replace(/\D/g, "");
                const numValue = parseInt(value) || 0;
                // 同时限制最小值和最大值
                value = Math.min(Math.max(numValue, 1), 5).toString();
                setArticleCount(value);
              }}
              onFocus={(e) => e.target.select()}
              className="w-20"
              placeholder="数量"
            />
            <span className="text-gray-700">篇</span>
          </div>
          <Button onClick={virHandleGenerate} disabled={isLoading}>
            {isLoading ? "生成中..." : "开始生产"}
          </Button>
        </div>
      </div>
      <GenerateDown batch={buildBatch} selectedType={selectedType} />
    </div>
  );
}
